package azalea.mqtt.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Font;
import java.awt.Color;

public class MqttClientPanel extends JPanel {

	private String clientName;
	MainApp topFather;

	/**
	 * Create the panel.
	 * 
	 * @param mainAppV2
	 * @param connName
	 */
	public MqttClientPanel(MainApp mainAppV2, String connName) {
		topFather = mainAppV2;
		clientName = connName;
		initialize();
	}

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private JTextField textFieldHost;
	private JTextField textFieldDefaultclientid;
	private JTextField txtAdmin;
	private JTextField textFieldPassword;
	private JTextField textFieldPort;
	private JButton btnNewButton;
	private JButton btnNewButton_1;
	private JLabel lblTopic;
	private JTextField textFieldtopic;
	private JButton button;
	private JButton button_1;
	private JPanel panel_1;
	private JScrollPane scrollPane;
	private JScrollPane scrollPane_1;
	/**
	 * @wbp.nonvisual location=447,527
	 */
	private final JTextArea textAreaSend = new JTextArea();
	private JTextArea textAreaRcv;
	private JButton btnNewButton_2;
	private JPanel panel_2;
	private JButton btnNewButton_3;
	private JButton btnNewButton_4;

	private MqttClient mqttClient;
	private JLabel label_tips;
	private JLabel lblNewLabel_5;
	private JTextField txtTest;
	private JTextArea rcvCommandtextArea;
	private JLabel lblNewLabel_6;
	private JTextField textFieldKeepLive;
	private JLabel lblQos;
	private JTextField textFieldQos;
	private JButton btnNewButton_5;
	private JLabel labelConnFlag;

	/**
	 * Launch the application.
	 */

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		// frmMqtt = new JFrame();
		// frmMqtt.setTitle("MQTT3.1.1客户端");
		// frmMqtt.setBounds(100, 100, 1058, 551);
		// frmMqtt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(new BorderLayout(0, 0));

		JPanel panel = new JPanel();
		this.add(panel, BorderLayout.NORTH);
		
		labelConnFlag = new JLabel("·");
		labelConnFlag.setForeground(Color.GRAY);
		labelConnFlag.setFont(new Font("微软雅黑", Font.BOLD, 25));
		panel.add(labelConnFlag);

		JLabel lblNewLabel = new JLabel("主机地址");
		panel.add(lblNewLabel);

		textFieldHost = new JTextField();
		textFieldHost.setText("192.168.0.127");
		panel.add(textFieldHost);
		textFieldHost.setColumns(20);

		JLabel lblNewLabel_4 = new JLabel("端口");
		panel.add(lblNewLabel_4);

		textFieldPort = new JTextField();
		textFieldPort.setText("1883");
		panel.add(textFieldPort);
		textFieldPort.setColumns(10);

		JLabel lblNewLabel_1 = new JLabel("客户端ID");
		panel.add(lblNewLabel_1);

		textFieldDefaultclientid = new JTextField();
		textFieldDefaultclientid.setText("DefaultClientID");
		panel.add(textFieldDefaultclientid);
		textFieldDefaultclientid.setColumns(10);

		JLabel lblNewLabel_2 = new JLabel("用户名");
		panel.add(lblNewLabel_2);

		txtAdmin = new JTextField();
		txtAdmin.setText("admin");
		panel.add(txtAdmin);
		txtAdmin.setColumns(10);

		JLabel lblNewLabel_3 = new JLabel("密码");
		panel.add(lblNewLabel_3);

		textFieldPassword = new JTextField();
		textFieldPassword.setText("123456");
		panel.add(textFieldPassword);
		textFieldPassword.setColumns(10);

		btnNewButton = new JButton("连接");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				connect();
			}
		});

		lblQos = new JLabel("Qos");
		panel.add(lblQos);

		textFieldQos = new JTextField();
		textFieldQos.setText("0");
		panel.add(textFieldQos);
		textFieldQos.setColumns(2);

		lblNewLabel_6 = new JLabel("keeplive");
		panel.add(lblNewLabel_6);

		textFieldKeepLive = new JTextField();
		textFieldKeepLive.setText("60");
		panel.add(textFieldKeepLive);
		textFieldKeepLive.setColumns(5);
		panel.add(btnNewButton);

		btnNewButton_1 = new JButton("断开");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				disconnect();
			}
		});
		panel.add(btnNewButton_1);

		lblTopic = new JLabel("TOPIC");
		panel.add(lblTopic);

		textFieldtopic = new JTextField();
		textFieldtopic.setText("test");
		panel.add(textFieldtopic);
		textFieldtopic.setColumns(30);

		button = new JButton("订阅");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				subscribe();
			}
		});
		panel.add(button);

		button_1 = new JButton("取消订阅");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dissubscribe();
			}
		});
		panel.add(button_1);

		panel_1 = new JPanel();
		this.add(panel_1, BorderLayout.EAST);

		btnNewButton_2 = new JButton("清  空");
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clearRcv();
			}
		});
		panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));

		btnNewButton_5 = new JButton("复  制");
		btnNewButton_5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				copy2clipBoard();
			}
		});
		panel_1.add(btnNewButton_5);
		panel_1.add(btnNewButton_2);

		rcvCommandtextArea = new JTextArea();
		panel_1.add(rcvCommandtextArea);
		textAreaSend.setColumns(10);

		scrollPane = new JScrollPane(textAreaSend);
		scrollPane.setPreferredSize(new Dimension(scrollPane.getWidth(), 200));
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		// scrollPane.setPreferredSize(new Dimension());
		this.add(scrollPane, BorderLayout.SOUTH);

		panel_2 = new JPanel();
		scrollPane.setColumnHeaderView(panel_2);

		btnNewButton_3 = new JButton("以文本发送");
		btnNewButton_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				sendTxt();
			}
		});

		lblNewLabel_5 = new JLabel("发送 TOPIC：");
		panel_2.add(lblNewLabel_5);

		txtTest = new JTextField();
		txtTest.setText("test");
		panel_2.add(txtTest);
		txtTest.setColumns(60);
		panel_2.add(btnNewButton_3);

		btnNewButton_4 = new JButton("以二进制发送");
		panel_2.add(btnNewButton_4);

		label_tips = new JLabel("    ");
		panel_2.add(label_tips);

		scrollPane_1 = new JScrollPane();
		scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		this.add(scrollPane_1, BorderLayout.CENTER);

		textAreaRcv = new JTextArea();
		textAreaRcv.setColumns(10);
		scrollPane_1.setViewportView(textAreaRcv);
	}

	private void connect() {
		synClientInfo();
		if (mqttClient != null) {
			try {
				mqttClient.disconnect();
			} catch (Exception e) {
			}
		}
		mqttClient = new MqttClient(this);
		try {
			mqttClient.connect(textFieldHost.getText(), textFieldPort.getText(), textFieldDefaultclientid.getText(),
					txtAdmin.getText(), textFieldPassword.getText());
			
		} catch (Exception e) {
			printInfo(e.toString());
			JOptionPane.showMessageDialog(null, "连接失败", "错误", JOptionPane.ERROR_MESSAGE);
		}
	}

	private void disconnect() {
		try {
			synClientInfo();
			mqttClient.disconnect();
		} catch (Exception e) {
			printInfo(e.toString());
		} finally {
			mqttClient = null;
		}
	}

	private void subscribe() {
		try {
			synClientInfo();
			mqttClient.subscribe(textFieldtopic.getText());
		} catch (Exception e) {
			printInfo(e.toString());
		} finally {

		}
	}

	private void dissubscribe() {
		try {
			mqttClient.dissubscribe(textFieldtopic.getText());
		} catch (Exception e) {
			printInfo(e.toString());
		} finally {

		}
	}

	private void clearRcv() {
		textAreaRcv.setText("");
		rcvCommandtextArea.setText("");
	}

	private void sendTxt() {
		try {
			String topic = txtTest.getText();
			String txt = textAreaSend.getText();
			mqttClient.sendTxt(topic, txt);
		} catch (Exception e) {
			printInfo(e.toString());
		}

	}

	public void updateRcv(String rcv) {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(() -> {
			// textAreaRcv.a
			String currentText = textAreaRcv.getText();
			if (currentText == null) {
				currentText = "";
			}
			textAreaRcv.setText(currentText + "\r\n" + rcv);
		});
	}

	public void updateRcvPublish(String topic, String rcv) {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(() -> {
			// textAreaRcv.a
			String currentText = textAreaRcv.getText();
			if (currentText == null) {
				currentText = "";
			}
			String date = sdf.format(new Date());
			String content = currentText + "\r\n" + date + " " + topic + "\r\n" + rcv;
			textAreaRcv.setText(content);
		});
	}

	public void printInfo(String info) {
		SwingUtilities.invokeLater(() -> {
			// textAreaRcv.setText(currentText+"\r\n"+rcv);
			label_tips.setText(info);
		});
	}

	public void updateRcvCommand(String command) {
		SwingUtilities.invokeLater(() -> {
			// textAreaRcv.setText(currentText+"\r\n"+rcv);
			String cmmd = command + "\r\n" + rcvCommandtextArea.getText();
			rcvCommandtextArea.setText(cmmd);
		});
	}

	public void close() {
		this.disconnect();
	}

	public void synClientInfo() {
		MqttClientModel mqttClientModel = new MqttClientModel();
		mqttClientModel.setClientId(this.textFieldDefaultclientid.getText());
		mqttClientModel.setClientName(clientName);
		mqttClientModel.setHost(this.textFieldHost.getText());
		mqttClientModel.setPassword(this.textFieldPassword.getText());
		mqttClientModel.setPort(this.textFieldPort.getText());
		mqttClientModel.setUserName(this.txtAdmin.getText());
		mqttClientModel.setKeepLive(textFieldKeepLive.getText());
		mqttClientModel.setTopic(textFieldtopic.getText());
		mqttClientModel.setQos(textFieldQos.getText());
		topFather.synClientInfo(mqttClientModel);
	}

	public void initByModel(MqttClientModel model) {
		// TODO Auto-generated method stub
		clientName = model.getClientName();
		textFieldDefaultclientid.setText(model.getClientId());
		textFieldHost.setText(model.getHost());
		textFieldPassword.setText(model.getPassword());
		textFieldPort.setText(model.getPort());
		txtAdmin.setText(model.getUserName());
		textFieldKeepLive.setText(model.getKeepLive());
		textFieldtopic.setText(model.getTopic());
		textFieldQos.setText(model.getQos()==null?"0":model.getQos());
	}

	public int getKeepLive() {
		String txt = textFieldKeepLive.getText();
		try {
			return Integer.parseInt(txt);
		} catch (Exception e) {
			return 0;
		}

	}
	public int getQos() {
		String txt = textFieldQos.getText();
		try {
			return Integer.parseInt(txt);
		} catch (Exception e) {
			return 0;
		}

	}
	public void copy2clipBoard() {
		StringSelection selection = new StringSelection(textAreaRcv.getText());
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		clipboard.setContents(selection, null);
	}

	public void connectFail() {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(() -> {
			// textAreaRcv.setText(currentText+"\r\n"+rcv);
			labelConnFlag.setForeground(Color.gray);
		});
		
	}

	public void connectSuccess() {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(() -> {
			// textAreaRcv.setText(currentText+"\r\n"+rcv);
			labelConnFlag.setForeground(Color.green);
		});
	}
}
